<template>
  <div class="my_header">
    <div class="head_logo">
      <img src="../../assets/studen/images/header_logo.png" alt="" srcset="" />
    </div>
    <div class="mytest IsOverTime" v-if="taskType == '2'">
      <dl class="timer_button">
        <dd>倒计时: &nbsp;{{ hours }}: {{ minutes }}: {{ seconds }}</dd>
      </dl>
      <dl class="finsh_button" @click="showComfirmDialog = true">
        <dd>结束竞赛</dd>
      </dl>
    </div>
    <div class="mytest">
      <router-link to="/student/Intelligent_evaluation" v-if="taskType == '1'">
        <dl class="username">
          <dd><img src="../../assets/studen/images/head_zncp.png" alt="" srcset="" /></dd>
          <dd>智能测评</dd>
        </dl>
      </router-link>
      <router-link to="/student/data_scene/monitoring_center" v-if="taskType == '1'">
        <dl class="loginout">
          <dd><img src="../../assets/studen/images/head_jkzx.png" alt="" srcset="" /></dd>
          <dd>监控中心</dd>
        </dl>
      </router-link>
      <el-dropdown class="dowloand_list">
        <dl class="username" @click="openUserDialog()">
          <dd><img src="../../assets/studen/images/user.png" alt="" srcset="" /></dd>
          <dd>{{ user.username }} &#9660</dd>
        </dl>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item command="a">
              <dl class="finsh_button" @click="handleShowTaskList('open')" style="width: 100%;">
                <dd><img src="../../assets/studen/images/head_task.png" alt="" srcset="" /></dd>
                <dd>我的任务</dd>
              </dl>
            </el-dropdown-item>
            <el-dropdown-item command="b">
              <dl class="loginout" @click="LoginOut()" style="width: 100%;">
                <dd><img src="../../assets/studen/images/out.png" alt="" srcset="" /></dd>
                <dd>退出</dd>
              </dl>
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>

    </div>
  </div>

  <el-dialog v-model="RepotVisible" :close-on-click-modal="false" width="30%" @close="CloseApplication(userRef)">
    <template #header>
      <h2 style="text-align: left;color:#6489CF">个人信息</h2>
    </template>
    <el-tabs type="border-card" v-model="TabsActiveName">
      <el-tab-pane label="个人信息" name="1">
        <el-form ref="userRef" :model="userForm" label-width="80px" :rules="rules" v-if="TabsActiveName == '1'">
          <el-form-item label="班级" prop="class">
            <el-input placeholder="班级" v-model="userForm.class" disabled />
          </el-form-item>
          <el-form-item label="账号" prop="account">
            <el-input placeholder="账号" disabled v-model="userForm.account" />
            <!-- <el-button type="text">身份证</el-button> -->
          </el-form-item>
          <el-form-item label="姓名" prop="name">
            <el-input placeholder="姓名" v-model="userForm.name" />
          </el-form-item>
          <el-form-item label="性别" prop="sex">
            <el-radio-group v-model="userForm.sex" class="ml-4">
              <el-radio label='1' size="large">男</el-radio>
              <el-radio label='2' size="large">女</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="学号" prop="studentNumber">
            <el-input placeholder="学号" v-model="userForm.studentNumber" />
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input placeholder="手机号" v-model="userForm.phone" />
          </el-form-item> <el-form-item label="邮箱" prop="mail">
            <el-input placeholder="邮箱" v-model="userForm.mail" />
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="修改密码" name="2">
        <el-form ref="userRef" :model="userForm" label-width="80px" :rules="passwordRules" v-if="TabsActiveName == '2'">
          <el-form-item label="旧密码" prop="oldPassword">
            <el-input clearable v-model="userForm.oldPassword" placeholder="旧密码" />
          </el-form-item>
          <el-form-item label="新密码" prop="newPassword">
            <el-input clearable v-model="userForm.newPassword" placeholder="新密码" />
          </el-form-item>
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input clearable v-model="userForm.confirmPassword" placeholder="确认密码" />
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="SubmitUser(userRef)">确定</el-button>
        <el-button @click="CloseApplication(userRef)"> 取消 </el-button>
      </span>
    </template>
  </el-dialog>

  <el-dialog align-center width="20%" @close="showComfirmDialog = false" v-model="showComfirmDialog"
    :close-on-click-modal="false">
    <template #header>
      <h2 style="text-align: center;">提示</h2>
    </template>
    <span style="text-align: center;"> 您确定提交吗？提交后就不能再进行操作！</span>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="handleFinsh()" :loading="btnloading">确定</el-button>
        <el-button @click="showComfirmDialog = false"> 取消 </el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 查看我的任务 -->
  <el-dialog :z-index="4000" v-model="showAllTaskDialog" :close-on-click-modal="false" class="ismydialog" width="70%"
    @close="showAllTaskDialog = false">
    <template #header>
      <div class="ismydialog_hed"></div>
    </template>
    <dl class="head_task">
      <dd style="width: 48px;"></dd>
      <dd class="trone">序号</dd>
      <dd class="trtow">序号名称</dd>
      <dd class="trthere">分值</dd>
      <dd class="trthere">{{ taskType == '1' ? '得分' : '' }}</dd>
      <dd class="trfour">操作</dd>
    </dl>
    <el-scrollbar height="500px">
      <div class="head_taskbody">
        <div class="task_boone" v-for="(u, o) in taskList" :key="o">
          <p class="task_boone_title">{{ u.moduleName }}</p>
          <div class="task_boone_list">
            <dl class="task_listdl" :class="{ 'bottom_none': u.taskItems.length >= 3 }" v-for="(t, y) in u.taskItems"
              :key="y">
              <dd class="trone">{{ y + 1 }}</dd>
              <dd class="trtow">{{ t.taskName }}</dd>
              <dd class="trthere">{{ t.score }}</dd>
              <dd class="trthere">{{ taskType == '1' ? t.result : '' }}</dd>
              <dd class="trfour">
                <el-button class="btn_bag " @click="OpenTask(t)" :class="{ btn1: t.status == 1 || t.status == 2 }"
                  :loading="btnloading">{{ t.status == 1 ? "继续" :
                    "开启" }}</el-button>
                <el-button class="btn_bag" :class="{ btn2: t.status == 1 || t.status == 2 }" @click="RedoTask(t)"
                  :loading="btnloading">重做</el-button>
                <el-button class="btn_bag" :class="{ btn3: t.status == 1 }" @click="SubmitTask(t)"
                  :loading="btnloading">提交</el-button>
              </dd>
            </dl>
          </div>
        </div>
      </div>
    </el-scrollbar>
  </el-dialog>
</template>
<script setup lang="ts">
import { emitter } from "@/utils/mitt";
import { useRouter } from "vue-router";
import { useUserStore, useUserStoreHook } from "@/store/modules/user";
import { ref, reactive, onMounted, nextTick } from "vue";
import { decrypt } from "@/utils/asc";
import qs from "qs";
import { storageSession, storageLocal } from "@pureadmin/utils";
import { getUserInfo, changePassword, updateUserInfo } from "@/api/user";
import {
  onSubmitCompetition,
  GetUserAllTask,
  OpentaskOnOpen,
  OpentaskOnRedo,
  OpentaskOnSubmit
} from "@/api/stu/taskManage";
import { ElMessage, FormInstance, ElMessageBox } from "element-plus";
const router = useRouter();
const RepotVisible = ref(false)
const userRef = ref();
const user = useUserStore();
const userForm = reactive({
  class: "",
  account: "",
  name: "",
  sex: null,
  studentNumber: "",
  phone: "",
  mail: "",
  oldPassword: "",
  newPassword: "",
  confirmPassword: ""
})
const TabsActiveName = ref<string>("1");
const isShowTimer = ref(false)
let timer
const hours = ref(null)
const minutes = ref(null)
const seconds = ref(null)
const showComfirmDialog = ref(false) //确认结束任务弹窗
const showAllTaskDialog = ref(false) //查看我的任务弹窗
const taskList = ref() //任务列表
const btnloading = ref(false)
const taskType = localStorage.getItem("taskType");
function CloseApplication(row: FormInstance | undefined) {
  TabsActiveName.value = "1"
  RepotVisible.value = false;
  row.resetFields();
}

const rules = {
  class: [
    {
      required: true,
      message: "请输入班级！",
      trigger: ["blur", "change"]
    }
  ],
  account: [
    {
      required: true,
      message: "请输入账号！",
      trigger: ["blur", "change"]
    }
  ],
  sex: [
    {
      required: true,
      message: '请选择性别',
      trigger: ["blur", "change"],
    }
  ],
  name: [
    {
      required: true,
      validator: (rule: any, value: any, callback: () => void) => {
        if (/^[\u4e00-\u9fa5]+$/.test(userForm.name) === false) {
          return callback(new Error('姓名只能输入中文'))
        } else {
          // 校验通过
          return callback()
        }
      },
      trigger: ["blur", "change"],
    }
  ],
  studentNumber: [
    {
      required: true,
      validator: (rule: any, value: any, callback: () => void) => {
        if (/^[a-zA-Z0-9]+$/.test(userForm.studentNumber) === false) {
          return callback(new Error('学号只能是数字和字母'))
        } else {
          // 校验通过
          return callback()
        }
      },
      trigger: ["blur", "change"],
    }
  ],
  phone: [
    {
      required: true,
      validator: (rule: any, value: any, callback: () => void) => {
        if (/^1[0-9]{10}$/.test(userForm.phone) === false) {
          return callback(new Error('请输入正确的手机号'))
        } else {
          // 校验通过
          return callback()
        }
      },
      trigger: ["blur", "change"],
    }
  ],
  mail: [
    {
      required: true,
      validator: (rule: any, value: any, callback: () => void) => {
        if (/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(userForm.mail) === false) {
          return callback(new Error('请输入正确邮箱'))
        } else {
          // 校验通过
          return callback()
        }
      },
      trigger: ["blur", "change"],
    }
  ],
}

const passwordRules = {
  oldPassword: [
    {
      required: true,
      validator: (rule: any, value: any, callback: () => void) => {
        if (/^[a-zA-Z0-9]+$/.test(userForm.oldPassword) === false) {
          return callback(new Error('旧密码只能是数字和字母'))
        } else {
          // 校验通过
          return callback()
        }
      },
      trigger: ["blur", "change"],
    }
  ],
  newPassword: [
    {
      required: true,
      validator: (rule: any, value: any, callback: () => void) => {
        if (/^[a-zA-Z0-9]+$/.test(userForm.newPassword) === false) {
          return callback(new Error('新密码只能是数字和字母'))
        } else {
          // 校验通过
          return callback()
        }
      },
      trigger: ["blur", "change"],
    }
  ],
  confirmPassword: [
    {
      required: true,
      validator: (rule: any, value: any, callback: () => void) => {
        if (/^[a-zA-Z0-9]+$/.test(userForm.confirmPassword) === false) {
          return callback(new Error('重复密码只能是数字和字母'))
        } else if (userForm.confirmPassword !== userForm.newPassword) {
          return callback(new Error('两次输入密码不一致'))
        }
        else {
          // 校验通过
          return callback()
        }
      },
      trigger: ["blur", "change"],
    }
  ],
}

function LoginOut() {
  user.logOut();
}
//打开弹窗获取个人信息
async function openUserDialog() {
  const userId = decrypt(localStorage.getItem("userId"));
  // console.log(userId);

  let data = qs.stringify({ userId: userId })
  let res = await getUserInfo(data)
  if (res.success) {
    userForm.class = res.data.className
    userForm.account = res.data.userId
    userForm.name = res.data.userName
    userForm.sex = res.data.sex + ''
    userForm.studentNumber = res.data.studentNumber
    userForm.phone = res.data.telePhone
    userForm.mail = res.data.email
    RepotVisible.value = true;
  } else {
    ElMessage.error(res.msg)
  }
}
//提交更改
async function SubmitUser(row: FormInstance | undefined) {
  (row as any).validate(async valid => {
    if (!valid) return;
    //修改用户信息
    if (TabsActiveName.value == '1') {
      const userId = decrypt(localStorage.getItem("userId"));
      const data = {
        userId: userId,
        userName: userForm.name,
        sex: Number(userForm.sex),
        telePhone: userForm.phone,
        email: userForm.mail,
        studentNumber: userForm.studentNumber
      }
      let res = await updateUserInfo(data)
      if (res.success) {
        ElMessage.success(res.msg);
        row.resetFields();
        let data = qs.stringify({
          userId: userId,
        })
        let res1 = await getUserInfo(data)
        if (res.success) {
          useUserStoreHook().SET_USERNAME(res1.data.userName);
          //防止持久化登录刷新时候没更新username的值
          // 从存储中获取对象
          const sessionData = storageLocal().getItem('user-info');
          // 修改username的值
          sessionData.username = res1.data.userName;
          // 更新存储中的对象
          storageLocal().setItem('user-info', sessionData);

        }
        RepotVisible.value = false;
      } else {
        ElMessage.error(res.msg);
      }
    }
    //修改密码
    if (TabsActiveName.value == '2') {
      const userId = decrypt(localStorage.getItem("userId"));
      const data = {
        userId: userId,
        oldPassword: userForm.oldPassword,
        newPassword: userForm.newPassword,
        confirmPassword: userForm.confirmPassword,
      }
      let res = await changePassword(data)
      if (res.success) {
        ElMessage.success(res.msg);
        row.resetFields();
        RepotVisible.value = false;
      } else {
        ElMessage.error(res.msg);
      }
    }
  })
}

// 开启任务
async function OpenTask(row) {
  const data = qs.stringify({ taskId: row.taskId });
  btnloading.value = true;
  const res = await OpentaskOnOpen(data);
  if (res.success) {

    sessionStorage.setItem("moduleId", JSON.stringify(row.moduleId))
    emitter.emit("Refresh_module")
    nextTick(() => {
      router.push({
        path: "/student/data_scene/MapPage",
        query: {
          planId: row.planId,
          taskId: row.taskId
        }
      });
    })
    handleShowTaskList('refresh')
    btnloading.value = false;
    showAllTaskDialog.value = false;
  } else {
    ElMessage.error(res.msg)
    setTimeout(() => { btnloading.value = false; }, 1500)
  }
}

// 重做任务
async function RedoTask(row) {
  if (!row.status) {
    ElMessage.warning("未开启任务")
    return
  }

  ElMessageBox({
    title: '提示', //MessageBox 标题
    closeOnClickModal: false,
    message: '是否确定重做当前任务?', //MessageBox 消息正文内容
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    const data = qs.stringify({ taskId: row.taskId });
    btnloading.value = true;
    const res = await OpentaskOnRedo(data);
    if (res.success) {
      btnloading.value = false;
      sessionStorage.setItem("moduleId", JSON.stringify(row.moduleId))
      emitter.emit("Refresh_module")
      setTimeout(() => {
        nextTick(() => {
          router.push({
            path: "/student/data_scene/MapPage",
            query: {
              planId: row.planId,
              taskId: row.taskId
            }
          });
        })
      })
      handleShowTaskList('refresh')
      ElMessage({
        type: 'success',
        duration: 500,
        message: res.msg
      })
      showAllTaskDialog.value = false;
    } else {
      setTimeout(() => { btnloading.value = false; }, 1500)
      ElMessage({
        type: 'error',
        duration: 500,
        message: res.msg
      })
    }
  }).catch(() => { })


}
// 提交任务
async function SubmitTask(row) {
  if (!row.status) {
    ElMessage.warning("未开启任务")
    return
  }
  const data = qs.stringify({ taskId: row.taskId });
  btnloading.value = true;
  const res = await OpentaskOnSubmit(data);
  if (res.success) {
    btnloading.value = false;
    ElMessage.success(res.msg)
    nextTick(() => {
      router.push({ path: "/stuindex" });
    })
    handleShowTaskList('open')
  } else {
    setTimeout(() => { btnloading.value = false; }, 1500)
    ElMessage.error(res.msg)
  }
}

onMounted(async () => {
  CompetitionTime()
})

function CompetitionTime() {
  nextTick(() => {
    const currentTime = new Date();
    const taskType = user.taskType
    const startTime = new Date(user.competitionStartTime)
    const endTime = new Date(user.competitionEndTime)
    const timeDiff = Math.floor((endTime - currentTime) / 1000);
    //是竞赛任务并且要已经开始
    if (taskType == 2 && currentTime > startTime && timeDiff > 0) {
      // 展示倒计时
      let countdown = timeDiff
      // 更新倒计时的函数
      const updateCountdown = async () => {
        countdown--;
        // 判断倒计时是否为0
        if (countdown <= 0) {
          // 清除定时器
          handleFinsh()
        } else {
          // 将倒计时转换为时分秒格式
          hours.value = Math.floor(countdown / 3600).toString().padStart(2, '0');
          minutes.value = Math.floor((countdown % 3600) / 60).toString().padStart(2, '0')
          seconds.value = (countdown % 60).toString().padStart(2, '0');
          if (!isShowTimer.value) {
            isShowTimer.value = true
          }
        }
      };
      // 创建定时器，每秒更新倒计时的值
      timer = setInterval(updateCountdown, 1000)
    }
  })
}

async function handleFinsh() {
  btnloading.value = true;
  let res = await onSubmitCompetition()
  if (res.success) {
    btnloading.value = false;
    clearInterval(timer);
    isShowTimer.value = false
    // LoginOut()
    router.push({
      path: "/studentmark",
      query: { score: res.data }
    });
  } else {
    setTimeout(() => { btnloading.value = false; }, 1500)
    ElMessage.error(res.msg)
  }
}


async function handleShowTaskList(state) {
  if (state === 'open') {
    let res = await GetUserAllTask();
    if (res.success) {
      taskList.value = res.data;
      showAllTaskDialog.value = true;
    } else {
      ElMessage.error(res.msg)
    }
  }
}
</script>
<style scoped lang="scss">
@import url(@/style/breadcrumbIcon.scss);

// @import url(@/style/task_list.scss);
.trfour :deep(.el-button) {
  border: none;
}

:deep(.el-button.is-loading:before) {
  background-color: transparent
}

.my_header {
  width: 100%;
  background-color: white;
  height: 100%;
  display: flex;
  justify-content: space-between;
  padding: 0 20px;
  position: relative;

  .head_logo {
    line-height: 70px;
    display: flex;
    align-items: center;
  }


  .mytest,
  dl {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-left: 15px;
  }

  .mytest {

    .timer_button,
    .finsh_button,
    .username,
    .loginout {
      cursor: pointer;
      // width: 180px;
      padding: 0px 5px;
      background: url(@/assets/studen/images/user_bag_n.png) no-repeat;
      background-size: 100% 100%;
      display: flex;
      align-items: center;


      dd {
        margin: 0 5px;
        color: #000;
        font-size: 22px;
        text-align: center;
        line-height: 38px;
        padding: 2px;

        img {
          width: 35px;
          height: 35px;
        }
      }
    }
  }
}

.IsOverTime {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  margin: auto;
}

.head_task {
  width: 100%;
  height: 100%;
  background-color: #F3F7FE;
  margin: 10px auto;
  // padding: 10px 0;
  line-height: 42px;
  display: inline-flex;

  dd {
    color: #3A5990;
    font-size: 16px;
    font-weight: bold;
    text-align: center;
  }
}

.head_taskbody {
  width: 100%;

  .task_boone {
    width: 100%;
    display: inline-flex;
    border: 1px solid #3A5990;
    border-radius: 5px;
    margin-bottom: 10px;

    .task_boone_title {
      width: 46px;
      font-size: 18px;
      color: #3A5990;
      text-align: center;
      -webkit-writing-mode: vertical-lr;
      -ms-writing-mode: tb-lr;
      writing-mode: vertical-lr;
      line-height: 46px;
      padding: 10px 0;
      letter-spacing: 2px;
      border-right: 1px solid #3A5990;
    }
  }

  .task_boone_list {
    width: calc(100% - 46px);

    .task_listdl {
      display: inline-flex;
      width: 100%;
      height: 45px;
      line-height: 45px;
      // border-top: 1px solid #3A5990;
      border-bottom: 1px solid #3A5990;

      // &:first-child {
      //   border-top: none;
      // }

      dd {
        text-align: center;
      }
    }
  }
}

.trone {
  width: 15%;
}

.trtow {
  width: 35%;
}

.trthere {
  width: 20%;
}

.trfour {
  width: 35%;
}


:deep(.el-dropdown-menu__item) {
  width: 180px;
  padding: 5px;

  dl {
    display: flex;
    align-items: center;
    // margin: 0 5px;
    color: #000;
    font-size: 18px;
    // text-align: center;
    line-height: 32px;
    padding: 2px;

    dd {
      margin-right: 10px;

      img {
        width: 35px;
        height: 35px;
      }
    }
  }
}

.ismydialog {
  .ismydialog_hed {
    height: 60px;
    background: #E9F3FF;
  }
}

.bottom_none {
  &:last-child {
    border-bottom: none !important;
  }
}
</style>
<style>
.ismydialog .el-dialog__header {
  padding: 0 !important;
  margin-right: 0 !important;
}

.ismydialog .el-icon.el-dialog__close {
  background-color: #A9AFB6;
  border-radius: 50px;
  color: white;
  font-weight: bold;
  font-size: 16px;
}

.ismydialog .el-dialog__body {
  padding: 10px 20px;
}

@media screen and (max-width: 1600px) {
  .ismydialog.el-dialog {
    --el-dialog-margin-top: 7vh;
  }
}
</style>
